import _ from 'lodash';
import * as React from 'react';
import {observer} from 'mobx-react';
import {SortableContainer, SortableElement, arrayMove} from 'react-sortable-hoc';
import './SortableGridStyle.less';
import {SudokuIconBean} from '../../model/sudoku/Sudoku';

const SortableItem = observer(SortableElement(({item}) => {
    const icon = _.includes(item.icon, "http") ? item.icon : `http://${item.icon}`

    return (
        <li className="iconItem">
            <img src={icon} alt="图片"/>
            <span className="iconName" title={item.text}>{item.text}</span>
        </li>
    )
}));

const SortableList = observer(SortableContainer(({items}) => {
    return (
        <ul className="iconContainer">
            {items.map((item, index) => (
                <SortableItem key={`item-${index}`} index={index} item={item}/>
            ))}
        </ul>
    );
}));

@observer
export class SortableGrid extends React.Component<{ data: Array<SudokuIconBean>; changeItem: Function; }, any> {
    onSortEnd = ({oldIndex, newIndex}) => {
        const {data, changeItem} = this.props;

        changeItem(arrayMove(data, oldIndex, newIndex));
    };

    render() {
        const {data} = this.props;

        return (
            <SortableList
                items={data}
                onSortEnd={this.onSortEnd}
                axis="xy"/>
        );
    }
}